package service

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"sync"
	"user_srv/basic/config"
)

// MapService 统一高德API服务
type MapService struct {
	Provider string // 一般为"amap"
	APIKey   string
}

var amapOnce sync.Once
var amapInstance *MapService

// GetAmapService 单例获取高德服务
func GetAmapService() *MapService {
	amapOnce.Do(func() {
		amapInstance = &MapService{
			Provider: "amap",
			APIKey: config.AppCong.Amap.Key,
		}
	})
	return amapInstance
}

// GetAddressFromCoords 调用高德API逆地理编码，返回地名
func (s *MapService) GetAddressFromCoords(lat, lng float64) (string, error) {
	url := fmt.Sprintf(
		"https://restapi.amap.com/v3/geocode/regeo?location=%f,%f&key=%s&radius=1000&extensions=all",
		lng, lat, s.APIKey,
	)
	resp, err := http.Get(url)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}
	var result struct {
		Status    string `json:"status"`
		Info      string `json:"info"`
		Regeocode struct {
			FormattedAddress string `json:"formatted_address"`
		} `json:"regeocode"`
	}
	if err = json.Unmarshal(data, &result); err != nil {
		return "", err
	}
	if result.Status != "1" {
		return "", fmt.Errorf("高德API错误: %s", result.Info)
	}
	return result.Regeocode.FormattedAddress, nil
}
